package com.sinitek.sirm.elfinder.support.spring.converter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.converter.ConditionalGenericConverter;
import org.springframework.util.NumberUtils;

import java.util.Collections;
import java.util.Set;

/**
 * 自定义Number转换
 * SpringMvc 内置转换器对于int等基本类型不支持空字符串，该转换器解决此问题，如果是空字符，则默认转换成0
 *
 *
 * @author yg.huang
 * @version v1.0
 *          DATE  2016/11/24
 */

public class CustomNumberConverter implements ConditionalGenericConverter {

    private final ConversionService conversionService;

    public  CustomNumberConverter(ConversionService conversionService){

        this.conversionService=conversionService;
    }




    @Override
    public Set<ConvertiblePair> getConvertibleTypes() {
        return Collections.singleton(new ConvertiblePair(String.class, Number.class));
    }

    @Override
    public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
      return  String.class.isAssignableFrom(sourceType.getType())&&Number.class.isAssignableFrom(targetType.getObjectType());
    }

    @Override
    public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
        Object target=null;
        Class<Number> targetClass= (Class<Number>) targetType.getObjectType();
        if (source == null|| StringUtils.isBlank(source.toString())) {
            if(targetType.getType().isPrimitive()){
                /*
                   如果是基本类型，则转换成0
                 */
                target= NumberUtils.parseNumber("0",targetClass);
                return  target;
            }
            else{
                return null;
            }
        }
        target= NumberUtils.parseNumber(source.toString(),targetClass);

        return target;
    }


}